//
//  StatusListViewModel.swift
//  Weibo
//
//  Created by 孙成宇 on 15/12/2.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import AFNetworking


class StatusListViewModel: NSObject {

    class func loadData(since_id: Int, max_id: Int, finished: (statues: [Status]?) -> () ) {


        let urlString = "2/statuses/home_timeline.json"



        guard let token = userAccountViewModel().token else{

            SVProgressHUD.showErrorWithStatus("你暂时未登陆")
            return

        }
        var  parameters = ["access_token": token]

        if since_id > 0 {


       parameters["since_id"] = "\(since_id)"

        }
        if max_id > 0 {

      parameters["max_id"] = "\(max_id - 1)"

        }




        NetworkTools.sharedTools.requestJSONDict(.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in

            if error != nil {
                finished(statues: nil)
                return

            }
            guard let array = result!["statuses"] as?[[String:AnyObject]] else{
                print("数据有误")
                finished(statues: nil)
                return



            }
            var list = [Status]()

            for item in array {
                let s = Status(dict: item)
                list.append(s)


            }
            finished(statues: list)

            cacheStatusSingleImage(list, finished: finished)


        }

    }



    class  func cacheStatusSingleImage(array:[Status],finished: (statues: [Status]?) -> ()) {
        if array.count == 0 {


            return
        }


        let group = dispatch_group_create()



        for s in array {

            if let urls = s.pictureURLs {
                if urls.count != 1 {
                    
                    continue
                }
                
                dispatch_group_enter(
                    group)
                SDWebImageManager.sharedManager().downloadImageWithURL(urls.first, options: [], progress: nil, completed: {
                    
                    (_,_,_,_,_) -> Void in
                    //   print("单张下载成功")
                    dispatch_group_leave(group)
                    
                    
                    
                })
            }
            
        }
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
            // print("完成了所有图片的下载")
            
            
            
            finished(statues: array)
        }
        
        
        
    }
    
}

